package security.core.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.filter.GenericFilterBean;

import security.core.filter.handler.LoginProcessHandler;
import security.core.filter.handler.LoginResultHandler;
import security.core.manager.AuthenticationManager;
import security.debug.RBACLogger;

public class LoginFilter extends GenericFilterBean {
	private String loginProcessURL;
	private String loginRedirectURL;
	private String loginPage;
	private AuthenticationManager authenticationManager;
	private LoginResultHandler loginResultHandler;
	private LoginProcessHandler loginProcessHandler;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		if (RBACLogger.debug()) {
			RBACLogger.log("LoginFilter#doFilter is called!");
		}
		if (!isLogined(request) && !isLoginRequest(request)) {
			((HttpServletResponse)response).sendRedirect(loginPage);
		} else if (!isLoginRequest(request)) {
			chain.doFilter(request, response);
		} else {
			Boolean result = loginProcessHandler.login(request, response, authenticationManager);
			loginResultHandler.onLoginResult(request, response, result, loginRedirectURL);
		}
	}
	
	public Boolean isLogined(ServletRequest request) {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpSession session = httpRequest.getSession();
		if (session.getAttribute("RBAC_USER_DETAIL") != null) {
			return true;
		}
		return false;
	}
	
	public Boolean isLoginRequest(ServletRequest request) {
		if (RBACLogger.debug()) {
			RBACLogger.log("LoginFilter#isLoginRequest is called!");
			RBACLogger.log("requesting url is [" + ((HttpServletRequest)request).getRequestURI() + "]");
		}
		return ((HttpServletRequest)request).getRequestURI().equals(loginProcessURL);
	}

	// setters
	public void setLoginProcessURL(String loginProcessURL) {
		this.loginProcessURL = loginProcessURL;
	}

	public void setLoginRedirectURL(String loginRedirectURL) {
		this.loginRedirectURL = loginRedirectURL;
	}

	public void setLoginPage(String loginPage) {
		this.loginPage = loginPage;
	}

	public void setAuthenticationManager(AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}

	public void setLoginResultHandler(LoginResultHandler loginResultHandler) {
		this.loginResultHandler = loginResultHandler;
	}

	public void setLoginProcessHandler(LoginProcessHandler loginProcessHandler) {
		this.loginProcessHandler = loginProcessHandler;
	}
}
